from app import create_app
from extentions import db, cors, flaskRedis
from flask_migrate import Migrate
from werkzeug.exceptions import MethodNotAllowed, NotFound, RequestTimeout
from exceptions.handle_exception import handle_exception
from app.api.index import indexApi
from app.backend.main import mainApi

app = create_app()

db.init_app(app)
cors.init_app(app)
flaskRedis.init_app(app)

migrate = Migrate(app, db)

def register_url(view, endpoint, url, pk='id', pk_type='int'):
    view_func = view.as_view(endpoint)
    app.add_url_rule(url, defaults={pk: None}, view_func=view_func, methods=['GET',])
    app.add_url_rule(url, view_func=view_func, methods=['POST',])
    app.add_url_rule('%s<%s:%s>' % (url, pk_type, pk), view_func=view_func, methods=['GET', 'PUT', 'DELETE'])

register_url(indexApi, 'index_api', '/v1/api/index/', pk='index_id')     
register_url(mainApi, 'backend_api', '/v1/api/main/', pk='id')

app.register_error_handler(NotFound, handle_exception)
app.register_error_handler(MethodNotAllowed, handle_exception)
app.register_error_handler(RequestTimeout, handle_exception)

if __name__ == '__main__': 
    app.run()